/*
   Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
   distributed with this work for additional information
   regarding copyright ownership.  The ASF licenses this file
   to you under the Apache License, Version 2.0 (the
   "License"); you may not use this file except in compliance
   with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an
   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   KIND, either express or implied.  See the License for the
   specific language governing permissions and limitations
   under the License. 
*/

package com.google.enterprise.gsa.crf;

import java.util.logging.Logger;

import javax.jdo.Query;
import com.google.enterprise.gsa.crf.DBClickRecord;
import com.google.enterprise.gsa.crf.PMF;
import javax.jdo.PersistenceManager;
import java.util.List;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @author luiscamacho
 *
 */
public class DBService extends Service {
    private static Logger log = null;

	/* (non-Javadoc)
	 * @see com.google.enterprise.gsa.crf.Service#init()
	 */
	@Override
	public void init() {
  
	}

	public DBService(){
        log = Logger.getLogger(DBService.class.getName());
	}
	
	/* (non-Javadoc)
	 * @see com.google.enterprise.gsa.crf.Service#logClick(java.lang.String[])
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void logClick(String[] params) {
		String date = super.now(getDateformat());
		String q = "";
		String ct = "";
		int r = 0;
		String url = "";
		int start = 0;
        //String frontend = null;
        
        for (int i = 0; i < params.length; i++) {
            String values[] = params[i].split("=");

            if (values[0].equals("q")){
            	q = (values.length > 1) ? values [1] : "";
            } else if (values[0].equals("ct")) {
                ct = (values.length > 1) ? values[1] : "";
            } else if (values[0].equals("r")) {
                r = (values.length > 1) ? Integer.parseInt(values[1]) : 0;
            } else if (values[0].equals("url")) {
                url = (values.length > 1) ? values[1] : "";
            } else if (values[0].equals("start"))
                start = (values.length > 1) ? Integer.parseInt(values[1]) : 0;
        }
        
        //URL and query decoding
        try {
        	q = URLDecoder.decode(URLDecoder.decode(q, "UTF-8"), "UTF-8");
			q = q.replace('+', ' ');
		} catch (UnsupportedEncodingException e) {
			q = "";
			e.printStackTrace();
		}
		
        try {
			url = URLDecoder.decode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			url = "";
			e.printStackTrace();
		}
        
        //Log click in DBClickRecord class
        DBClickRecord dbcr = new DBClickRecord(date, q, ct, r, url, start);
        
        PersistenceManager pm = PMF.get().getPersistenceManager();
 
        //Update query frequency class
        Query query = pm.newQuery(DBQueryFrequency.class);
        query.setFilter("query == currentQuery");
        query.declareParameters("String currentQuery");       
        //Update Clicks per row class
        
        Query queryCPR = pm.newQuery(DBClicksPerRow.class);
        queryCPR.setFilter("row == currentRow");
        queryCPR.declareParameters("Long currentRow");
        
        try {
            pm.makePersistent(dbcr);
            log.fine("Click logged in DB");

            if (ct.equals("load")){
	            List<DBQueryFrequency> results = (List<DBQueryFrequency>) query.execute(q);
	            DBQueryFrequency dbqf = null;
	            
	            if (results.isEmpty()) {
	            	log.fine("New query submitted: " + q);
	            	dbqf = new DBQueryFrequency(q, Long.valueOf(1));
	            } else{
	            	log.fine("Updating existing query: " + q);
	            	dbqf = results.get(0);
	            	dbqf.setFrequency(dbqf.getFrequency() + 1);
	            }
	        	if (!dbqf.equals(null)){
	        		pm.makePersistent(dbqf);
	        		log.fine("New query logged");
	        	}
            } else {
            	Long clickedRow = Long.valueOf(r + start);
            	
            	List<DBClicksPerRow> results = (List<DBClicksPerRow>) queryCPR.execute(clickedRow);
            	DBClicksPerRow dbcpr = null;
            	
	            if (results.isEmpty()) {
	            	log.fine("New clicked row: " + clickedRow);
	            	dbcpr = new DBClicksPerRow(clickedRow, Long.valueOf(1));
	            } else{
	            	log.fine("Updating existing clicked row: " + clickedRow);
	            	dbcpr = results.get(0);
	            	dbcpr.setClicks(dbcpr.getClicks() + 1);
	            }
	        	if (!dbcpr.equals(null)){
	        		pm.makePersistent(dbcpr);
	        		log.fine("Clicked row logged: " + clickedRow);
	        	}
            }
        } finally {
            pm.close();
        }
	}
}

